/**
 * ProjectName doctor
 * FileName ApiController.java
 * PackageName com.doctor.controller.api
 * Date 2017年6月13日 下午12:51:35
 * Copyright (c) 2015, lyg945@163.com All Rights Reserved.
 */
package com.doctor.controller.api;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.doctor.common.JsonResult;
import com.doctor.entity.Department;
import com.doctor.entity.Doctor;
import com.doctor.entity.Linkman;
import com.doctor.service.DeparmentService;
import com.doctor.service.DoctorService;
import com.doctor.service.LinkmanService;

@Controller
@RequestMapping("/api")
public class ApiController {

	@Resource
    private DoctorService doctorService;
    @Resource
	private DeparmentService deparmentService;
    @Resource
	private LinkmanService linkmanService;
    
    @PostMapping("/doctor-list")
    @ResponseBody
    public Page<Doctor> list(int pageNumber,long deparmentId) {
        Pageable pageable = new PageRequest(pageNumber,10);
        Page<Doctor> page = doctorService.findByDepartmentId(deparmentId,pageable);
        return page;
    }
	
	@PostMapping("/deparment-list")
	@ResponseBody
	public JsonResult deparmentList() {
		List<Department> list = null;
        try {
        	list = deparmentService.findAll();
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.fail(e.getMessage());
        }
        return JsonResult.ok("data", list);
    }
	
	@PostMapping("/sms-code")
	@ResponseBody
	public JsonResult smsCode(HttpServletRequest request,String mobile) {
		int code = deparmentService.smsCode(mobile);
		request.getSession().setAttribute("mobile", code);
        return JsonResult.ok();
    }
	
	@PostMapping("/register")
	@ResponseBody
	public JsonResult register(HttpServletRequest request,String code,Linkman linkman) {
		Integer sms = (Integer) request.getSession().getAttribute("mobile");
		if((sms == null) || sms.toString().length() < 6) {
			return JsonResult.fail("请先获取验证码");
		} else if(sms.toString().equals(code)){
			linkmanService.saveOrUpdate(linkman);
			return JsonResult.ok("提交成功");
		}else{
			return JsonResult.fail("验证码错误");
		}
    }
}
